package com.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client1 {
    public static void main(String[] args) {
        final String SERVER_IP = "localhost";
        final int PORT = 8888;

        try (Socket socket = new Socket(SERVER_IP, PORT);
             // 获取输入输出流
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);  // 自动刷新
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("已连接到服务端，输入消息开始对话 (输入 exit 退出)...");

            String userInput;
            while (true) {
                System.out.print("客户端 > ");
                userInput = scanner.nextLine();

                // 发送消息到服务端
                out.println(userInput);  // 使用 PrintWriter 发送消息

                if ("exit".equalsIgnoreCase(userInput)) {
                    break;
                }

                // 接收服务端响应
                String response = in.readLine();
                System.out.println("服务端 > " + response);
            }
        } catch (UnknownHostException e) {
            System.err.println("未知主机: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("连接失败: " + e.getMessage());
        }
    }
}
